package cn.wen.base.view.limit;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;

import cn.wen.base.R;


/**
 * 访淘宝的限时抢购的头部的View
 *
 <FrameLayout
 android:layout_width="match_parent"
 android:layout_height="80dp">

 <cn.carhouse.viewdemo.view.limit.LimitBgView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#333"
 app:limitBgCenterColor="#FF0000"
 app:limitBgItemCount="5" />

 <cn.carhouse.viewdemo.view.limit.LimitLayout
 android:id="@+id/view"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 app:limitItemCount="5">

 </cn.carhouse.viewdemo.view.limit.LimitLayout>
 </FrameLayout>
 */

public class LimitLayout extends HorizontalScrollView implements ViewPager.OnPageChangeListener {
    private static final int SCROLL_MSG = 0x0011;
    public static final int DELAYED_TIME = 100;
    private LimitTabView mContainer;
    private TabAdapter mAdapter;
    private int mPosition;// 当前的位置
    private int mScrollPosition;// 滚动的位置
    private ViewPager mViewPager;
    private boolean isScroll;// 表示 是不是用户划动ViewPager
    private int mItemCount = 5;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            smoothScrollTo(mScrollPosition * mContainer.getItemWidth(), 0);
            if (mViewPager != null) {
                mViewPager.setCurrentItem(mScrollPosition, false);
            }
            mPosition = mScrollPosition;
        }
    };

    public LimitLayout(Context context) {
        this(context, null);
    }

    public LimitLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LimitLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LimitLayout);
        mItemCount = array.getInt(R.styleable.LimitLayout_limitItemCount, mItemCount);
        array.recycle();
        mContainer = new LimitTabView(getContext());
        mContainer.setItemCount(mItemCount);
        addView(mContainer);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 测量自己和子View的宽高
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        measureChild(mContainer, widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }


    public void setAdapter(TabAdapter adapter) {
        if (adapter == null) {
            throw new NullPointerException("TabAdapter is null");
        }
        mAdapter = adapter;
        int count = mAdapter.getCount();
        for (int i = 0; i < count; i++) {
            View mItemView = mAdapter.getView(i, mContainer);
            mItemView.setFocusable(true);
            mContainer.addView(mItemView);
            itemClick(mItemView, i);
        }
        // 默认选中第一个位置
        mAdapter.onTabSelected(mContainer.getChildAt(mPosition), mPosition);
    }

    public void setAdapter(TabAdapter adapter, ViewPager viewPager) {
        setAdapter(adapter);
        this.mViewPager = viewPager;
        mViewPager.addOnPageChangeListener(this);
    }

    private void itemClick(View itemView, final int position) {
        itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                isScroll = true;
                // 会到--->>onScrollChanged
                smoothScrollTo(position * mContainer.getItemWidth(), 0);
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        isScroll = true;
        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        // 如果是用户划动ViewPager
        if (!isScroll) {
            return;
        }
        mScrollPosition = (l + mContainer.getItemWidth() / 2) / mContainer.getItemWidth();
        if (l - oldl <= 1) {
            // 说明是停止了
            mHandler.removeMessages(SCROLL_MSG);
            mHandler.sendEmptyMessageDelayed(SCROLL_MSG, DELAYED_TIME);
            return;
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        isScroll = false;
        int totalScroll = (int) ((position + positionOffset) * mContainer.getItemWidth());
        scrollTo(totalScroll, 0);
        isScroll = true;
    }

    @Override
    public void onPageSelected(int position) {
        isScroll = true;
        // 重置上一个位置
        mAdapter.onTabReset(mContainer.getChildAt(mPosition), mPosition);
        mPosition = position;
        // 选中当前位置
        mAdapter.onTabSelected(mContainer.getChildAt(mPosition), mPosition);

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
